﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    public class RepeatBuyStaController : BaseController<usersorder>
    {
        //
        // GET: /RepeatBuySta/
        protected admin CurrentUer
        {
            get { return Session["CurrentUer"] == null ? null : (admin)Session["CurrentUer"]; }
        }

        public ActionResult Test()
        {
            return View();
        }
        public override BLL.BaseBll<usersorder> bll
        {
            get
            {
                return new UsersOrderBll();
            }

        }

        StoreBll storeBll = new StoreBll();

        public class repeatCondition
        {
            public int shopID;
            public string shopName;
            public string ShopAddress;
            public int repeatNum;// 复购数量 

        }
        UserBll userBll = new UserBll();

        public class ListFlow
        {
            public int userCode { get; set; }
            public string wechatName { get; set; }

            public string userPhone { get; set; }

            public int visitorRate { get; set; }//访问频率
            public decimal? consumeMoney { get; set; }   //消费总金额

        }
        public class ListOrderDetail
        {
            public string orderCode;
            public string orderTime;
            public string waresCode;
            public string waresName;
            public long waresNumber;
            public decimal waresPrice;
            public decimal TotalPrice;

        }

        repeatCondition repeatModel = new repeatCondition();
        /// <summary>
        /// 各个店铺的  复购情况 
        /// </summary>  
        /// <returns></returns>
        public ActionResult RepeatGoNum(string sort, string date1, string date2)
        {
            //SELECT userCode, SUM(orderSumprice)+SUM(discountMoney),COUNT(*) FROM  usersorder WHERE DATE_FORMAT(orderTime, '%Y%m') = DATE_FORMAT(CURDATE( ) ,'%Y%m')  and storeid=10010	 		 and orderStatus=1					
            var listRepeat = new List<repeatCondition>();
            Expression<Func<usersorder, bool>> condition = x => x.orderStatus == 1;
            if (date1 != "" && date1 != null && date2 != "" && date2 != null)
            {
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                condition = x => x.orderStatus == 1 && x.orderTime >= datetime1 && x.orderTime <= datetime2;
            }
            else
                //查询本月 复购情况  的
            {
                //DateTime todayNow = DateTime.Now;
                //DateTime midnight = DateTime.Now;
                //midnight = midnight.Date;
               // condition = x => x.orderStatus == 1 && x.orderTime <= todayNow && x.orderTime >= midnight;
                int a= DateTime.Now.Month;
                condition = x => x.orderStatus == 1 && x.orderTime.Month==DateTime.Now.Month;
            }
            // 查询所有的 店铺   
            var shopList = storeBll.Search(x => x.storeStatus == 1).Select(x => new { x.storeid, x.storeName, x.storeDress }).ToList();
            //便利每一个店铺
            foreach (var item in shopList)
            {
                //一个店铺的订单列表  
                var orderlist = bll.Search(x => x.storeid == item.storeid).Where(condition);
                //根据 用户进行分组  .Select(x => new { x.FirstOrDefault().userCode,Count=x.Count()})
                var userOrder = orderlist.GroupBy(x => x.userCode).ToList();
                repeatCondition repeatModel = new repeatCondition();
                repeatModel.repeatNum = orderlist.Count() - userOrder.Count(); //把   userCode=0 的也算进去了
                repeatModel.ShopAddress = item.storeDress;
                repeatModel.shopID = item.storeid;
                repeatModel.shopName = item.storeName;
                listRepeat.Add(repeatModel);
                if (sort == "repeatNum")
                {
                    listRepeat = listRepeat.OrderByDescending(x => x.repeatNum).ToList();
                }
            }
            return Json(listRepeat, JsonRequestBehavior.AllowGet);
        }


        //获取每个客户的来访频次 
        public ActionResult GetFlowByShopID(string shopID, string date1, string date2 ,string  sort,string order)
        {
            var flowlist1 = new List<ListFlow>();             
            var flowlist = new List<ListFlow>();

            //1.先查出  本月的交易成功的订单信息
            int shopid = Convert.ToInt32(shopID);
            Expression<Func<usersorder, bool>> condition = x => x.orderStatus == 1 && x.storeid == shopid && x.userCode != 0;
            Expression<Func<user, bool>> condition2 = x => true;
            //如果为空 所有的时间 搜索条件  就默认查询本月的记录
            if (string.IsNullOrEmpty(date1) && string.IsNullOrEmpty(date2))
            {
                ////时间类型相关的数 据 转化为 string 类型的数据   以后 不同的计算机转化结果不同 ，这里不建议使用string 来比较时间相关的数据
                //DateTime todayNow = DateTime.Now; 
                //DateTime midnight = DateTime.Now;
                //midnight = midnight.Date;
                //condition = x => x.orderStatus == 1 && x.orderTime <= todayNow && x.orderTime >= midnight && x.storeid == shopid && x.userCode != 0;  && x.userCode != 0
                condition = x => x.orderStatus == 1 && x.storeid == shopid && x.orderTime.Month==DateTime.Now.Month;;
            }
            //如果日期  不为空
            if (date1 != "" && date2 != "")
            {
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                condition = x => x.orderStatus == 1 && x.orderTime >= datetime1 && x.orderTime <= datetime2 && x.storeid == shopid;
            }   
            var orderList2 = bll.Search(condition).GroupBy(x => x.userCode).Select(x => new { x.FirstOrDefault().userCode, visitorRate = x.Count(), consumeMoney = x.Sum(y => y.orderSumprice) });

            if (orderList2.Count() != 0)
            {
                foreach (var item in orderList2)    
                {
                    var userInfoList = userBll.Search(x => x.userCode == item.userCode).Select(x => new { x.wechatName, x.userPhone, x.userName,  x.userCode });
                    // 如果没有满足条件的 消费档次   接下来怎默写
                    if (userInfoList.Count() != 0)
                    {
                        ListFlow flowModel = new ListFlow();
                        flowModel.userCode = userInfoList.FirstOrDefault().userCode;                       
                        flowModel.wechatName = userInfoList.FirstOrDefault().wechatName;                      
                        flowModel.userPhone = userInfoList.FirstOrDefault().userPhone;
                        flowModel.visitorRate = item.visitorRate;
                        flowModel.consumeMoney = item.consumeMoney;
                        flowlist.Add(flowModel);
                    }
                    else
                    {
                        ListFlow flowModel = new ListFlow();
                        flowModel.userCode =0;                      
                        flowModel.wechatName = "未知";
                        flowModel.userPhone = "未知";
                        flowModel.visitorRate = item.visitorRate;
                        flowModel.consumeMoney = item.consumeMoney;
                        flowlist.Add(flowModel);
                    }
               }
          }
            if (sort == "consumeMoney"&&order=="desc")
            {
                flowlist1 = flowlist.OrderByDescending(x => x.consumeMoney).ToList();
            }
            if (sort == "consumeMoney" && order == "asc")
            {
                flowlist1 = flowlist.OrderBy(x => x.consumeMoney).ToList();
            }
            if (sort == "visitorRate" && order == "desc")
            {
                flowlist1 = flowlist.OrderByDescending(x => x.visitorRate).ToList();
            }
            if (sort == "visitorRate" && order == "asc")
            {
                flowlist1 = flowlist.OrderBy(x => x.visitorRate).ToList();
            }
            return Json(new { rows = flowlist1 }, JsonRequestBehavior.AllowGet);
        }
   
        OrderDetailsBll orderDetailBll = new OrderDetailsBll();

        WaresBll waresBll = new WaresBll();
         
        //获取客户的订单详细信息
        public ActionResult GetDetailByID(string userCode, string date1, string date2)
        {
            int codeUser = 0;
            if (userCode != "")
            {
                codeUser = Convert.ToInt32(userCode);
            }
            var listOrderDetailCode = new List<ListOrderDetail>();
            Expression<Func<usersorder, bool>> condition = x => x.orderStatus == 1;
            if (string.IsNullOrEmpty(date1) || string.IsNullOrEmpty(date1))
            {
                DateTime todayNow = DateTime.Now;
                DateTime midnight = DateTime.Now;
                midnight = midnight.Date;
                condition = x => x.orderStatus == 1 && x.orderTime <= todayNow && x.orderTime >= midnight;
            }
            //如果日期  不为空
            if (date1 != "" && date2 != "")
            {
                //string datetime1 = DateTime.Parse(model.Time1).ToShortDateString();        
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                condition = x => x.orderStatus == 1 && x.orderTime >= datetime1 && x.orderTime <= datetime2;
            }
            //对应的订单列表
            var orderList = bll.Search(x => x.userCode == codeUser).Where(condition).Select(x => new { x.orderCode }).ToList();
            //根据订单标号 查询对应的每笔订单的详细信息
            foreach (var item in orderList)
            {
                string orderCode = item.orderCode;
                //订单对应的详情信息
                var list = orderDetailBll.Search(x => x.orderCode == orderCode).ToList().Select(x => new { x.orderCode, x.waresCode, x.waresQuantity }).ToList();
                foreach (var itemDetail in list)
                {
                    ListOrderDetail detail = new ListOrderDetail();
                    detail.orderCode = itemDetail.orderCode;
                    detail.waresNumber = itemDetail.waresQuantity;
                    detail.waresCode = itemDetail.waresCode;
                    listOrderDetailCode.Add(detail);
                }
            }
            var listOrderDetail = new List<ListOrderDetail>();
            // listOrderDetailCode  对应的订单详情列表  
            var allOrderWares = listOrderDetailCode.GroupBy(x => x.waresCode).Select(x => new { x.FirstOrDefault().waresCode, x.FirstOrDefault().waresName, x.FirstOrDefault().waresPrice, waresNumber = x.Sum(y => y.waresNumber), }).ToList();

            foreach (var oneDetailCode in allOrderWares)
            {
                var list2 = waresBll.Search(x => x.waresCode == oneDetailCode.waresCode).Select(x => new { x.waresCode, x.waresName, x.waresPrice }).ToList();
                if (list2.Count != 0)
                {
                    ListOrderDetail detail = new ListOrderDetail();
                    detail.waresCode = oneDetailCode.waresCode;
                    detail.waresName = list2.FirstOrDefault().waresName;
                    detail.waresNumber = Convert.ToInt32(oneDetailCode.waresNumber);
                    detail.waresPrice = Convert.ToDecimal(list2.FirstOrDefault().waresPrice);
                    detail.TotalPrice = Convert.ToDecimal(list2.FirstOrDefault().waresPrice * oneDetailCode.waresNumber);
                    listOrderDetail.Add(detail);
                }
            }

            //foreach (var oneDetailCode in listOrderDetailCode)
            //{
            //    var list2 = waresBll.Search(x => x.waresCode == oneDetailCode.waresCode).Select(x => new { x.waresCode, x.waresName, x.waresPrice }).ToList();
            //    if (list2.Count != 0)
            //    {
            //        ListOrderDetail detail = new ListOrderDetail();
            //        detail.orderCode = oneDetailCode.orderCode;
            //        DateTime dt = bll.Search(x => x.orderCode == oneDetailCode.orderCode).Select(x => new { x.orderTime }).ToList().FirstOrDefault().orderTime;
            //        detail.orderTime = dt.ToString();
            //        detail.waresCode = oneDetailCode.waresCode;
            //        detail.waresName = list2.FirstOrDefault().waresName;
            //        detail.waresNumber = Convert.ToInt32(oneDetailCode.waresNumber);
            //        detail.waresPrice = Convert.ToDecimal(list2.FirstOrDefault().waresPrice);
            //        detail.TotalPrice = Convert.ToDecimal(list2.FirstOrDefault().waresPrice * oneDetailCode.waresNumber);
            //        listOrderDetail.Add(detail);
            //    }
            //}
            return Json(listOrderDetail);
        }


        public class userFolw
        {
            public int userCode { get; set; }
            public decimal money { get; set; }
            public int  num { get; set; } 
        }


        //获取每个客户的来访频次222
        public ActionResult GetFlowByShopID22(string shopID, string date1, string date2, string sort, string order)
        {
            StringBuilder sql = new StringBuilder();
            var flowlist1 = new List<ListFlow>();
            var flowlist = new List<ListFlow>();

            //1.先查出  本月的交易成功的订单信息
            int shopid = Convert.ToInt32(shopID);    

            //如果为空 所有的时间 搜索条件  就默认查询本月的记录
            if (string.IsNullOrEmpty(date1) && string.IsNullOrEmpty(date2))
            {
                sql.Append("SELECT userCode, SUM(orderSumprice)+SUM(discountMoney) as money,COUNT(*) as num FROM  usersorder WHERE DATE_FORMAT(orderTime, '%Y%m') = DATE_FORMAT(CURDATE( ) ,'%Y%m')  and storeid=" + shopid + " and orderStatus=1	GROUP BY userCode	");
            }
            //如果日期  不为空
            if (date1 != "" && date2 != "")
            {
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                sql.Append("SELECT userCode, SUM(orderSumprice)+SUM(discountMoney) as money,COUNT(*) as num FROM  usersorder WHERE    usersorder.orderTime BETWEEN '" + datetime1 + "' and '" + datetime2 + "'   and storeid=" + shopid + " and orderStatus=1	GROUP BY userCode	");
                //condition = x => x.orderStatus == 1 && x.orderTime >= datetime1 && x.orderTime <= datetime2 && x.storeid == shopid;
            }
            if (sort == "consumeMoney" && order == "desc")
            {
                sql.Append(" ORDER BY money  DESC ");
                //flowlist1 = flowlist.OrderByDescending(x => x.consumeMoney).ToList();
            }
            if (sort == "consumeMoney" && order == "asc")
            {
                sql.Append(" ORDER BY money  asc ");
                //flowlist1 = flowlist.OrderBy(x => x.consumeMoney).ToList();
            }
            if (sort == "visitorRate" && order == "desc")
            {
                sql.Append(" ORDER BY num  DESC ");
                //// flowlist1 = flowlist.OrderByDescending(x => x.visitorRate).ToList();
            }
            if (sort == "visitorRate" && order == "asc")
            {
                sql.Append(" ORDER BY num  ASC ");
                //flowlist1 = flowlist.OrderBy(x => x.visitorRate).ToList();
            }
            var orderList2 = bll.SearchBySQL<userFolw>(sql.ToString()).ToList();

            foreach (var item in orderList2)
            {
               // var userInfo = userBll.Search(x => x.userCode == item.userCode);

                string userSql = "select * from user where usercode=" + item.userCode + " ";
                var userInfo = userBll.SearchBySQL<user>(userSql);
                if (userInfo.Count() == 0)
                {
                    ListFlow flowModel = new ListFlow();
                    flowModel.userCode = 0;
                    flowModel.userPhone = "未知";
                    flowModel.wechatName = "未知";
                    flowModel.visitorRate = item.num;
                    flowModel.consumeMoney = item.money;
                    flowlist.Add(flowModel);
                }
                else
                {
                    ListFlow flowModel = new ListFlow();
                    flowModel.userCode = item.userCode;                   
                    flowModel.userPhone = userInfo.FirstOrDefault().userPhone;
                    flowModel.wechatName = userInfo.FirstOrDefault().wechatName;
                    flowModel.visitorRate = item.num;
                    flowModel.consumeMoney = item.money;
                    flowlist.Add(flowModel);
                }
            }
            return Json(new { rows = flowlist }, JsonRequestBehavior.AllowGet);
        }
    }
}
